package org.ai.demo.ocr.config;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;

public class CustomizedRemoteTokenServices extends RemoteTokenServices{
	
	protected final Logger logger = LoggerFactory.getLogger(CustomizedRemoteTokenServices.class);

	
	public CustomizedRemoteTokenServices() {
	}
	

	@Cacheable(value = "cache_token")
	@Override
	public OAuth2Authentication loadAuthentication(String accessToken)
			throws AuthenticationException, InvalidTokenException {
		String[] clientDetail = getClientDetailFromToken(accessToken);
		setClientId(clientDetail[0]);
		setClientSecret(clientDetail[1]);
		OAuth2Authentication authentication = null;
		try {
			authentication = super.loadAuthentication(accessToken);
		} catch (Exception e) {
			throw new InvalidTokenException(accessToken,e);
		}
		return authentication;
	}

	private String[] getClientDetailFromToken(String accessToken) {
		String[] tokenStrings = accessToken.split("\\.");
		String[] clientDetail = new String[2];
		clientDetail[0] = decodeBASE64(tokenStrings[1]);
		clientDetail[1] = decodeBASE64(tokenStrings[2]);
		return clientDetail;
		
	}
	
	private  String decodeBASE64(String encodedText){
		final Base64.Decoder decoder = Base64.getDecoder();
		String text = null; 
		try {
			text = new String(decoder.decode(encodedText), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error("CustomizedRemoteTokenServices:decodeBASE64" + e.getMessage());;
		}
        return text;
    }

	

}
